﻿using AutoMapper;
using Esosi.Register.Base;
using Esosi.Register.Base.Dtos;
using Esosi.Register.Hospital.HospitalPolicy;
using Esosi.Register.Hospital.Models;
using Esosi.Repository;
using Esosi.Repository.Models;
using Esosi.Repository.Tools;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Esosi.Register.Hospital
{
    /// <summary>
    /// 院内政策挂号
    /// </summary>
    public class RegisterCalcHospital : IRegisterCalc
    {
        private readonly IMapper _mapper;
        private readonly IRegisterCalcRespository _service;

        public RegisterCalcHospital(IMapper mapper, IRegisterCalcRespository registerCalcHospitalRespository)
        {
            _mapper = mapper;
            _service = registerCalcHospitalRespository;
        }

        public RegisterCalcTpoDto RegisterCalc(RegisterCalcTpiDto tpid)
        {
            try
            {
                //将挂号的通用入参转成 院内政策挂号入参
                var tpi = _mapper.Map<RegisterHospitalTpi>(tpid);
                //院内政策入参转为数据访问入参
                var calc = _mapper.Map<RegisterCalcModel>(tpi);

                //获得挂号费用
                var gps = _service.GetRegisterPricesAsync(calc).Result;

                tpi.FeeItems = gps.Select(p => new FeeItem
                {
                    ItemId = p.PriceId,
                    ItemName = p.PriceName,
                    Price = p.Price,
                    Amount = 1,
                    IFeeTypeCode = p.FeeTypeCode,
                    PolicyFeeTypeCode = p.PolicyFeeTypeCode
                });

                //拿到政策实体
                var gmChargePolicys = _service.GetHosptialProtol(tpi.BalanceType, tpi.PatientSubTypeId);
                //应用政策
                var paySums = gmChargePolicys.Select(p => ChargePolicyFactory.CreatePolicy(p).ApplyPolicy(tpi)).ToList();

                //var Result = _service.SaveRegisterJsonInfo(ObjectToJson(tpi));
                //返回政策结果
                var tpod = new RegisterHospitalTpo
                {
                    JsonGuid = _service.SaveRegisterJsonInfo(ObjectToJson(tpi)),
                    PaySums = paySums
                };

                //转界面出参
                return _mapper.Map<RegisterCalcTpoDto>(tpod);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return null;
            }
        }

        /// <summary>
        /// Register实体转Json
        /// </summary>
        /// <param name="tpi"></param>
        /// <returns></returns>
        private string ObjectToJson(RegisterHospitalTpi tpi)
        {
            RegisterBalanceJsonModel registerBalanceJsonModel = new RegisterBalanceJsonModel();

            var StrJson = CommonTools.getJsonByObject(registerBalanceJsonModel);

            return StrJson;
        }
    }
}